package com.ruoyi.quartz.task;

import com.ruoyi.adapayDiv.service.IAdapayDivService;
import com.ruoyi.adapayMember.domain.AdapayMember;
import com.ruoyi.adapayMember.service.IAdapayMemberService;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.domain.entity.Member;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.member.service.IMemberService;
import com.ruoyi.shopping.domain.*;
import com.ruoyi.shopping.service.*;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chengliang
 * @date 2022/8/5
 **/
@Component("withDrawTask")
public class WithDrawTask {

    @Autowired
    private IMallOrderMeshService meshService;
    @Autowired
    private IMallOrderService orderService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IMallCommentService commentService;
    @Autowired
    private IMallBindService bindService;
    @Autowired
    private IAdapayDivService divService;
    @Autowired
    private IAdapayMemberService adapayMemberService;
    @Autowired
    private IMallIntegralService integralService;
    @Autowired
    private IMallIntegralRecordService integralRecordService;

        public void autoConfirm(){
        Integer day = Integer.valueOf(configService.selectConfigByKey("auto_confirm"));
        List<MallOrder> orders = orderService.selectNeedAutoConfirm(day);
        if(orders.size()==0) return;
        Date date = new Date();
        orders.forEach(e->{
            e.setOrderState(DicConstants.ORDER_STATE_Received.getCode());
            e.setConfirmTime(date);
            orderService.updateMallOrder(e);
        });
        List<Long> collect = orders.stream().map(MallOrder::getMergeOrderId).distinct().collect(Collectors.toList());
        collect.forEach(e->{
            List<MallOrder> mallOrders =
                    orderService.selectMallOrderByMeshId(e);
            int count = 0;
            for (MallOrder order : mallOrders) {
                if(DicConstants.ORDER_STATE_Received.getCode().equals(order.getOrderState())){
                    count++;
                }
            }
            if(count == mallOrders.size()){
                MallOrderMesh mallOrderMesh = meshService.selectMallOrderMeshById(e);
                mallOrderMesh.setShipState(DicConstants.SYS_Y.getCode());
                mallOrderMesh.setOrderState(DicConstants.ORDER_STATE_Received.getCode());
                meshService.updateMallOrderMesh(mallOrderMesh);
            }
        });
    }

    public void autoFinished(){
        Integer day = Integer.valueOf(configService.selectConfigByKey("auto_comment"));
        List<MallOrder> orders = orderService.selectNeedFinished(day);
        if(orders.size()==0)return;
        BigDecimal bigDecimal = new BigDecimal("5");
        orders.forEach(e->{
            e.setOrderState(DicConstants.ORDER_STATE_FINISHED.getCode());
            e.setCommentStatus(DicConstants.SYS_Y.getCode());

            Member member = memberService.selectMemberById(e.getMemberId());
            MallComment mallComment = new MallComment();
            mallComment.setMemberNickName(member.getNickName());
            mallComment.setMemberId(member.getId());
            mallComment.setMemberHeadImg(member.getHeadImg());
            mallComment.setProductId(e.getProductId());
            mallComment.setCommentContent("默认好评");
            mallComment.setPlatformLevel(bigDecimal);
            mallComment.setOrderId(e.getId());
            commentService.insertMallComment(mallComment);
            mallComment.setProductName(e.getProductName());

            orderService.updateMallOrder(e);
            orderService.checkFinished(e.getMergeOrderId());

        });
       /* List<Long> collect = orders.stream().map(MallOrder::getMergeOrderId).distinct().collect(Collectors.toList());
        for (Long e : collect) {
            List<MallOrder> mallOrders =
                    orderService.selectMallOrderByMeshId(e);
            int count = 0;
            for (MallOrder order : mallOrders) {
                if (DicConstants.SYS_Y.getCode().equals(order.getCommentStatus())) {
                    count++;
                }
            }
            if (count == mallOrders.size()) {
                MallOrderMesh mallOrderMesh = meshService.selectMallOrderMeshById(e);
                mallOrderMesh.setOrderState(DicConstants.ORDER_STATE_FINISHED.getCode());
                mallOrderMesh.setCommentState(DicConstants.SYS_Y.getCode());
                meshService.updateMallOrderMesh(mallOrderMesh);
            }
        }*/
    }

    public void autoWithDraw(){
        List<MallOrderMesh> meshList = meshService.selectNeedWithDraw();
        if(meshList.size()==0)return;
        List<MallOrder> o = new ArrayList<>();
        meshList.forEach(e->{
            MallBind bind = bindService.selectMallBindByMemberId(e.getMemberId());
            if(bind == null) return;
            AdapayMember adapayMember = new AdapayMember();
            adapayMember.setStoreId(bind.getStoreId());
            List<AdapayMember> list = adapayMemberService.selectAdapayMemberList(adapayMember);
            if(list.size()>0){
                adapayMember = list.get(0);
            }else{
                return;
            }
            List<MallOrder> orders = orderService.selectMallOrderByMeshId(e.getId());
            for (MallOrder order : orders) {
                if(DicConstants.SYS_N.getCode().equals(order.getAfterSalesState())){
                    BigDecimal distribution = new BigDecimal(configService.selectConfigByKey("distribution")).divide(new BigDecimal("100"));
                    BigDecimal subtract = order.getPayPrice().multiply(distribution).setScale(2, RoundingMode.HALF_UP);
                    divService.mallOrderDiv(bind.getStoreId(),adapayMember,e,subtract);
                    o.add(order);
                }
                handleIntegral(e,o);
            }

        });
    }

    //获取积分处理
    private void handleIntegral(MallOrderMesh mesh,List<MallOrder> orders) {
        String consume=configService.selectConfigByKey("consume");
        if(StringUtils.isEmpty(consume)){
            return;
        }
        BigDecimal integral = Arith.getBigDecimal(consume);
        if(null==integral||integral.compareTo(BigDecimal.ZERO)==0){
            return;
        }
        MallOrder mallOrder = new MallOrder();
        mallOrder.setMemberId(mesh.getMemberId());
        mallOrder.setMergeOrderId(mesh.getId());
        BigDecimal total = BigDecimal.ZERO;
        for (MallOrder order : orders) {
            //缺少判断订单是否需要计算
            if(DicConstants.SYS_N.getCode().equals(order.getAfterSalesState())) {
                total = total.add(order.getPayPrice());
            }

        }
        if(total.compareTo( BigDecimal.ZERO)==0){
            return;
        }
        BigDecimal divide = total.divide(integral,0, BigDecimal.ROUND_DOWN);
        mesh.setGainIntegral(divide.longValue());
        mesh.setPayPrice(total);
        mesh.setPayState(DicConstants.SYS_N.getCode());
        MallIntegral mallIntegral = new MallIntegral();
        mallIntegral.setUserId(mesh.getMemberId());
        List<MallIntegral> mallIntegrals = integralService.selectMallIntegralList(mallIntegral);
        if(mallIntegrals.size()>0){
            MallIntegral in = mallIntegrals.get(0);
            in.setIntegralBalance(in.getIntegralBalance().add(divide));
            mallIntegral.setIntegralBalance(in.getIntegralBalance());
            integralService.updateMallIntegral(in);
        }else{
            mallIntegral.setIntegralBalance(divide);
            integralService.insertMallIntegral(mallIntegral);
        }
        MallIntegralRecord record = new MallIntegralRecord();
        record.setUserId(mesh.getMemberId());
        record.setDepict("商城消费"+mesh.getPayPrice().toString()+"元");
        record.setHandleType(DicConstants.INTEGRAL_TYPE_POINT.getCode());
        record.setHandleDirection("in");
        record.setHandleIntegral(divide);
        record.setIntegralBalance(mesh.getPayPrice());
        integralRecordService.insertMallIntegralRecord(record);
        orders.clear();
    }
}
